package com.katesoft.scale4j.rttp.jobs;

import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.log.LogFactory;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;

import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

/** @author kate2007 */
public class JobsUtility
{
    private static final Logger LOGGER = LogFactory.getLogger(JobsUtility.class);
    public static final String JOB_NAME = "JobsUtility.JOB_NAME";

    /*
    * Copy parameters that are of the correct type over to
    * {@link JobParameters}, ignoring jobName.
    *
    * @return a {@link JobParameters} instance
    */
    public static JobParameters covertJobParameters(Map<String, Object> jobDataMap,
                                                    boolean ignoreJobName)
    {
        JobParametersBuilder builder = new JobParametersBuilder();
        for (Entry<String, Object> entry : jobDataMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String) {
                if (value.equals(JOB_NAME)) {
                    if (!ignoreJobName) { builder.addString(key, (String) value); }
                }
                else {
                    builder.addString(key, (String) value);
                }
            }
            else if (value instanceof Float || value instanceof Double) {
                builder.addDouble(key, ((Number) value).doubleValue());
            }
            else if (value instanceof Integer || value instanceof Long) {
                builder.addLong(key, ((Number) value).longValue());
            }
            else if (value instanceof Date) {
                builder.addDate(key, (Date) value);
            }
            else {
                LOGGER.debug("JobDataMap contains [%s=%s] which are not job parameters (ignoring).", key, value);
            }
        }
        return builder.toJobParameters();
    }
}
